package com.spider.iceCream.spiderComponent.util;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class HttpRequestUtil {
    private CloseableHttpClient httpClient;
    private List<Header> headerList = new ArrayList<Header>();

    public HttpEntity getEntityByGetMethod(String url){
        initDefaultHeaders();
        httpClient = HttpClients.custom()
                .setRetryHandler(new DefaultHttpRequestRetryHandler())
                .setDefaultHeaders(headerList)
                .build();
        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        HttpGet get = new HttpGet(url);
        get.setConfig(defaultConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity httpEntity = response.getEntity();

        return  httpEntity;
    }
    public  String getContentByGetMethod(String url,String code){
        try {
            return EntityUtils.toString(getEntityByGetMethod(url),code);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public List<Header>initDefaultHeaders() {
        headerList.add(new BasicHeader("accept", "*/*"));
//        headerList.add(new BasicHeader("accept-encoding","***"));
//        headerList.add(new BasicHeader("accept-language","***"));
        //  headerList.add(new BasicHeader("if-modified-since", "***"));
        headerList.add(new BasicHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67"));
        return headerList;
    }

}
